package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.BeansException;
import com.yfq.springframework.beans.DisposableBean;
import com.yfq.springframework.beans.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 姚凤桥
 * @date 2023/1/8 17:09
 * @description
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    private final Map<String, Object> singletonMap = new HashMap<>();

    private final Map<String, DisposableBean> disposableBeans = new HashMap<>();

    @Override
    public void registerSingletonBean(String beanName, Object bean) {
        singletonMap.put(beanName, bean);
    }

    @Override
    public Object getSingletonBean(String beanName) {
        return singletonMap.get(beanName);
    }

    public void registerDisposableBean(String beanName, DisposableBeanAdapter disposableBeanAdapter) {
        disposableBeans.put(beanName,disposableBeanAdapter);
    }

    public void destroySingletons() {
        Set<String> keySet = this.disposableBeans.keySet();
        String[] disposableBeanNames = keySet.toArray(new String[0]);

        for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
            Object beanName = disposableBeanNames[i];
            DisposableBean disposableBean = disposableBeans.remove(beanName);
            try {
                disposableBean.destroy();
            } catch (Exception e) {
                throw new BeansException("Destroy method on bean with name '" + beanName + "' threw an exception");
            }
        }
    }

}
